package com.qf.point.service.impl;

import com.qf.common.core.entity.PointRule;
import com.qf.common.core.entity.Points;
import com.qf.common.core.utils.SpringBeanUtils;
import com.qf.common.core.utils.UserUtils;
import com.qf.point.mapper.PointsMapper;
import com.qf.point.service.PointRuleService;
import com.qf.point.service.PointsService;
import com.qf.user.service.UserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zdl
 * @date 2025/3/25
 */
@Service
public class PointsServiceImpl implements PointsService {
    @Resource
    private PointsMapper pointsMapper;
    @Resource
    private UserService userService;

    @Resource
    private PointRuleService pointRuleService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addPoint(Points points) {
        // 向积分记录表添加数据
        pointsMapper.insert(points);
        // 更新用户表中的point字段
        userService.updatePoint(points.getUid(), points.getPoint());
    }

    @Override
    public void remoteAddPoint(Integer pointType, Integer uid) {
        List<PointRule> pointRuleList = pointRuleService.ruleList();
        PointRule pointRule = pointRuleList.stream()
                .filter(item -> item.getPointType().equals(pointType))
                .findFirst()
                .orElse(null);
        if (pointRule != null) {
            Points points = new Points();
            points.setPoint(pointRule.getPoint());
            points.setPointType(pointType);
            points.setUid(uid == null ? UserUtils.getUser() : uid);
            // 针对事务失效，通过上下文获取bean
            PointsService bean = SpringBeanUtils.getBean(PointsService.class);
            bean.addPoint(points);
        }
    }
}
